"""
FPS data fetcher for CPU-GPU-Game combinations
"""
from models.database import CPU, GPU, Game, FPSPrediction, init_db
from config.database_config import get_db_url
from src.fetcher import process_cpu_range
from sqlalchemy import and_
import logging
import argparse

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

def main():
    # 解析命令行参数
    parser = argparse.ArgumentParser(description='FPS data fetcher for CPU-GPU-Game combinations')
    parser.add_argument('--start-cpu-id', type=int, required=True, help='Start CPU ID')
    parser.add_argument('--end-cpu-id', type=int, required=True, help='End CPU ID')
    args = parser.parse_args()
    
    # Initialize database session
    session = init_db(get_db_url())
    
    try:
        # Get total count of combinations to process
        total_cpus = session.query(CPU).filter(
            and_(
                CPU.status == 1,
                CPU.id >= args.start_cpu_id,
                CPU.id <= args.end_cpu_id
            )
        ).count()
        total_gpus = session.query(GPU).filter(GPU.status == 1).count()
        total_games = session.query(Game).filter(Game.status == 4).count()
        
        # Get count of processed combinations
        processed_count = session.query(
            FPSPrediction.cpu_id,
            FPSPrediction.gpu_id,
            FPSPrediction.game_id
        ).filter(
            FPSPrediction.cpu_id >= args.start_cpu_id,
            FPSPrediction.cpu_id <= args.end_cpu_id
        ).group_by(
            FPSPrediction.cpu_id,
            FPSPrediction.gpu_id,
            FPSPrediction.game_id
        ).count()
        
        # 计算进度百分比
        total_combinations = total_cpus * total_gpus * total_games
        progress_percentage = (processed_count / total_combinations * 100) if total_combinations > 0 else 0
        
        logger.info(f"Task Summary:")
        logger.info(f"CPU Range: {args.start_cpu_id} - {args.end_cpu_id}")
        logger.info(f"Valid CPUs: {total_cpus}")
        logger.info(f"Valid GPUs: {total_gpus}")
        logger.info(f"Valid Games: {total_games}")
        logger.info(f"Progress: {processed_count}/{total_combinations} ({progress_percentage:.2f}%)")
        
        # 处理指定范围的 CPU
        process_cpu_range(session, args.start_cpu_id, args.end_cpu_id)
                
    except Exception as e:
        logger.error(f"Error in main process: {str(e)}")
    finally:
        session.close()

if __name__ == "__main__":
    main() 